package com.email.box.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.http.HttpCookie;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;

import java.util.HashMap;
import java.util.Map;

public class CookieUtil {

    private static final String KEY = "jwt";
    private static final String SECRET = "35c67738-33db-4d1c-8987-d43811e04d17";
//    private static final String SECRET = "undefined";

    public static Long getOperator(ServerWebExchange serverWebExchange) {
        try {
            MultiValueMap<String, HttpCookie> cookies = serverWebExchange.getRequest().getCookies();
            HttpCookie cookie = cookies.getFirst(KEY);
            String jwtToken = cookie.getValue();
            return getOperator(jwtToken);
        } catch (NullPointerException e) {
            return null;
        }
    }

    public static String getOperatorStr(ServerWebExchange serverWebExchange) {
        Long operator = CookieUtil.getOperator(serverWebExchange);
        String operatorStr;
        if (operator == null) {
            operatorStr = "system auto";
        } else {
            operatorStr = operator.toString();
        }
        return operatorStr;
    }

    /**
     * 从 jwtToken 中解出 account_id
     *
     * @param jwtToken jwtToken
     * @return account_id
     */
    public static Long getOperator(String jwtToken) {
        DecodedJWT jwt = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(jwtToken);
        Map<String, Claim> map = new HashMap<>(jwt.getClaims());
        return map.get("account_id").asLong();
    }

    public static void main(String[] args) {
        //柳美云
        String jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJoYXNfbW9iaWxlIjp0cnVlLCJ2YWxpZF9tb2JpbGUiOmZhbHNlLCJjb2RlIjowLCJjaXR5IjoiLeivt-mAieaLqS0iLCJyZWFsX25hbWUiOiLmn7Pnvo7kupEiLCJhY2NvdW50X25hbWUiOiJFMDAwMDEwMTAiLCJuaWNrbmFtZSI6IkUwMDAwMTAxMCIsImNvbXBhbnkiOiLmlbDmja7kv53pmpzpg6giLCJvcmdfbmFtZSI6IuacnemYs-awuOe7rSIsInByb3YiOiIt6K-36YCJ5oupLSIsImhhc19lbWFpbCI6dHJ1ZSwiZW1haWwiOiJsaXVteUBnby1nb2FsLmNvbSIsImhhc19wYXNzd29yZCI6dHJ1ZSwiYXJlYSI6bnVsbCwiemlwIjpudWxsLCJoYXNfd3giOmZhbHNlLCJhZGRyZXNzIjpudWxsLCJzZXgiOm51bGwsIm1vYmlsZSI6IjE4NjAxNjc3MDY5IiwiYmlydGgiOm51bGwsInRlbGVwaG9uZSI6bnVsbCwiYXZhdGFyIjpudWxsLCJtZXNzYWdlIjoi55m75b2V5oiQ5YqfIiwidG9rZW4iOiJmOGZhOWI4YmZjOTc0MTg0YjM1Y2I3NDk4YzFkYjFmNiIsImhhc19vcmciOmZhbHNlLCJhY2NvdW50X2lkIjozMzE4OTEsImFwcGxpY2F0aW9uIjowLCJ3b3JrX2FkZHJlc3MiOm51bGwsIm9yZ19pZCI6NCwiZHV0eSI6Iui0qOajgOWRmCIsInVuaWZpZWRfcHVyY2hhc2UiOmZhbHNlfQ.M9fCHw06g1QEwkjNoNig-Us3kFyAUq88h78WTLhJpZY";
        System.out.println(getOperator(jwt));
    }
}
